var config = require('../config/config.js');

function formatTime(date) {
    let year = date.getFullYear(),
        month = date.getMonth() + 1,
        day = date.getDate(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds();


    return [year, month, day].map(formatNumber).join('/') +
        ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
    n = n.toString();
    return n[1] ? n : '0' + n
}

/**
 * 获取系统信息,获取成功后:
 * 1.存入本地存储;
 * 2.存入App.globalData内存
 * @param successCb Function
 */
function getSystemInfo() {
    return new Promise((resolve, reject) => {
        let app = getApp();
        let info = app.globalData.systemInfo;
        if (info) {
            resolve(info);
        }
        wx.getSystemInfo({
            success: function (res) {
                wx.setStorage({
                    key: config.storage.keySystemInfo,
                    data: res
                });
                app.globalData.systemInfo = res;
                resolve(res);
            },
            fail: function (res) {
                reject(res);
            },
            complete: function (res) {
            },
        });
    })
}

/**
 * 获取本地存储的SessionId
 */
function getSessionId() {
    let sessionId;
    try {
        sessionId = wx.getStorageSync(config.storage.keySessionId);
    } catch (e) {
    }
    return sessionId;
}


function getAuthState() {
    return new Promise((resolve, reject) => {
        wx.getSetting({
            success: (res) => {
                let authSetting = res.authSetting;
                resolve(!!authSetting['scope.userInfo']);
            },
            fail: () => {
                resolve(false);
            }
        })
    })
}
module.exports = {
    formatTime: formatTime,
    getSystemInfo: getSystemInfo,
    getSessionId: getSessionId,
    getAuthState:getAuthState
};
